package com.xps.charmingshop.view.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.jude.utils.JUtils;
import com.xps.charmingshop.R;
import com.xps.charmingshop.bean.ClassificationBean;
import com.xps.charmingshop.bean.MapBean;
import com.xps.charmingshop.bean.RegisterBean;
import com.xps.charmingshop.bean.VerificationBean;
import com.xps.charmingshop.date.net.UserNetWorks;
import com.xps.charmingshop.servicer.UserService;
import com.xps.charmingshop.servicer.UserServiceImpl;
import com.xps.charmingshop.utils.AppCommond;
import com.xps.charmingshop.utils.DensityUtil;
import com.xps.charmingshop.utils.DownTimer;
import com.xps.charmingshop.view.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.Subscriber;

/**
 * Created by MI on 2018/1/19.
 */

public class RegisterActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.actionbar_tv_title)
    TextView actionbarTvTitle;
    @BindView(R.id.Edit_Email)
    EditText EditEmail;
    @BindView(R.id.Edit_Name)
    EditText EditName;
    @BindView(R.id.Edit_Classification)
    TextView EditClassification;
    @BindView(R.id.Edit_Branch)
    EditText EditBranch;
    @BindView(R.id.Edit_TheMain)
    EditText EditTheMain;
    @BindView(R.id.Edit_Password)
    EditText EditPassword;
    @BindView(R.id.Edit_Confirm)
    EditText EditConfirm;
    @BindView(R.id.Edit_Telephone)
    EditText EditTelephone;
    @BindView(R.id.Edit_Verification)
    EditText EditVerification;
    @BindView(R.id.Edit_License)
    ImageView EditLicense;
    @BindView(R.id.Edit_City)
    EditText EditCity;
    @BindView(R.id.Edit_Detailed)
    EditText EditDetailed;
    @BindView(R.id.Province_City)
    EditText ProvinceCity;
    Dialog bottomDialog;
    ViewGroup.MarginLayoutParams params;
    TextView XiCe_pickPhoto;
    TextView XiJi_takePhoto;
    TextView cancel_TextView;
    @BindView(R.id.Image_Head)
    ImageView ImageHead;
    @BindView(R.id.But_OK)
    TextView ButOK;
    @BindView(R.id.Verification_TextView)
    TextView VerificationTextView;
    @BindView(R.id.Image_Detailed)
    ImageView ImageDetailed;
    //TakePhoto
    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private Uri imageUri;  //图片保存路径
    private InvokeParam invokeParam;
    private UserService userService = new UserServiceImpl();
    private String imageUriStr = "";
    DownTimer timer;
    public static int Interval = 1000;
    View longinDialogView;
    LayoutInflater layoutInflater;
    LinearLayout Layout_Classification;
    String StrClassification;
    AlertDialog dialog;
    String ImagePath;
    String ImagePathStr = "1";

    @Override
    protected int getLayout() {
        return R.layout.activity_register;
    }

    @Override
    protected void setData() {
        actionbarTvTitle.setText("注册店铺");
        actionbarTvTitle.setTextColor(getResources().getColor(R.color.white));
    }

    @Override
    protected void init(Bundle inBundle) {
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        initData();
        bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 16f);
        params.bottomMargin = DensityUtil.dp2px(this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setText("相机");
        XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setText("相册");
        cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        layoutInflater = LayoutInflater.from(RegisterActivity.this);
        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
        dialog = builder.create();
        longinDialogView = layoutInflater.inflate(R.layout.dialog_classification, null);
        dialog.setView(longinDialogView);
        Layout_Classification = longinDialogView.findViewById(R.id.Layout_Classification);
        getClassification();
    }


    @OnClick({R.id.actionbar_iv_back, R.id.Image_Detailed, R.id.But_OK, R.id.Image_Head, R.id.Verification_TextView, R.id.Edit_Classification, R.id.Edit_License})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.But_OK:
                if (!ableGoNext()) return;
                if (EditPassword.getText().toString().equals(EditConfirm.getText().toString())) {
                    showDialogNoCancel();
                    getRegister();
                } else {
                    JUtils.Toast("两次密码不同");
                }
                break;
            case R.id.Image_Head:
                ImagePathStr = "1";
                OnClick();
                break;
            case R.id.Verification_TextView:
                getVerification();
                break;
            case R.id.Edit_Classification:
                showDialog();
                break;
            case R.id.Edit_License:
                ImagePathStr = "2";
                OnClick();
                break;
            case R.id.Image_Detailed:
                startActivity(new Intent(RegisterActivity.this, DetailedActivity.class));
                break;
        }
    }

    boolean ableGoNext() {
        if (!isEmail(EditEmail.getText().toString())) {
            JUtils.Toast("请输入正确邮箱地址");
            return false;
        } else if (TextUtils.isEmpty(EditName.getText().toString())) {
            JUtils.Toast("请输入店铺名称");
            return false;
        } else if (TextUtils.isEmpty(EditClassification.getText().toString())) {
            JUtils.Toast("请输入店铺分类");
            return false;
        } else if (TextUtils.isEmpty(EditBranch.getText().toString())) {
            JUtils.Toast("请输入店铺分店名");
            return false;
        } else if (TextUtils.isEmpty(EditTheMain.getText().toString())) {
            JUtils.Toast("请输入店铺主营");
            return false;
        } else if (TextUtils.isEmpty(EditPassword.getText().toString())) {
            JUtils.Toast("请输入密码");
            return false;
        } else if (TextUtils.isEmpty(EditConfirm.getText().toString())) {
            JUtils.Toast("请再次输入密码");
            return false;
        } else if (!isMobileNO(EditTelephone.getText().toString())) {
            JUtils.Toast("请输入正确联系方式");
            return false;
        } else if (TextUtils.isEmpty(EditVerification.getText().toString())) {
            JUtils.Toast("请输入验证码");
            return false;
        } else if (TextUtils.isEmpty(ImagePath)) {
            JUtils.Toast("请上传营业执照");
            return false;
        } else if (TextUtils.isEmpty(EditDetailed.getText().toString())) {
            JUtils.Toast("请输入详细地址");
            return false;
        } else if (imageUriStr.equals("")) {
            JUtils.Toast("请上传图像");
            return false;
        }


        return true;
    }

    public boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }

    public boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);

        return m.matches();
    }

    public void getRegister() {
        UserNetWorks.getRegister("1", imageUriStr, EditEmail.getText().toString(), EditName.getText().toString(), StrClassification, EditBranch.getText().toString(), EditTheMain.getText().toString(), EditPassword.getText().toString(), EditConfirm.getText().toString(), EditTelephone.getText().toString(), EditVerification.getText().toString(), ImagePath, ProvinceCity.getText().toString(), EditCity.getText().toString(), EditDetailed.getText().toString(), AddressLng, AddressLat, new Subscriber<RegisterBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onNext(RegisterBean registerBean) {
                if (registerBean.getReturn_code().equals("SUCCESS")) {
                    dissmisDialog();
                    finish();
                    JUtils.Toast(registerBean.getReturn_msg());
                } else if (registerBean.getReturn_code().equals("FAIL")) {
                    dissmisDialog();
                    JUtils.Toast(registerBean.getReturn_msg());
                }
            }
        });
    }

    public String AddressLat;
    public String AddressLng;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppCommond a) {
        if (!AppCommond.check(a)) return;
        for (String activityName : a.getAcNameList()) {
            if (activityName.equals(getClass().getSimpleName())) {
                EditDetailed.setText(MapBean.Address);
                AddressLat = MapBean.AddressLat;
                AddressLng = MapBean.AddressLng;
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unreg();
    }

    void unreg() {
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    void OnClick() {
        bottomDialog.show();
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                bottomDialog.dismiss();
            }
        });
        XiJi_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                bottomDialog.dismiss();
            }
        });
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        String iconPath = result.getImage().getOriginalPath();

        if (ImagePathStr.equals("1")) {
            Glide.with(RegisterActivity.this).load(iconPath)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .bitmapTransform(new CropCircleTransformation(RegisterActivity.this))
                    .into(ImageHead);
        } else if (ImagePathStr.equals("2")) {
            Glide.with(RegisterActivity.this).load(iconPath)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//禁用磁盘缓存
                    .skipMemoryCache(true)
                    .bitmapTransform(new CropCircleTransformation(RegisterActivity.this))
                    .into(EditLicense);
        }

        getUploadImage(iconPath);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Toast.makeText(RegisterActivity.this, "Error:" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeCancel() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    private void initData() {
        //获取TakePhoto实例
        takePhoto = getTakePhoto();
        //设置裁剪参数
        cropOptions = new CropOptions.Builder().setAspectX((int) 0.5).setAspectY((int) 0.5).setWithOwnCrop(false).create();
        //设置压缩参数
        compressConfig = new CompressConfig.Builder().setMaxSize(1 * 1).setMaxPixel(1).create();
        takePhoto.onEnableCompress(compressConfig, true);  //设置为需要压缩
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File Gallery = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Uri.fromFile(Gallery);
    }

    public void getUploadImage(String imageUri) {
        Uri uri = getImageContentUri(RegisterActivity.this, getFilePath(imageUri));
        if (uri == null) {
            Toast.makeText(this, "你没有选择任何图片", Toast.LENGTH_LONG).show();
        } else {
            String path = null;
            String[] pojo = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(uri, pojo, null, null, null);
            if (cursor != null) {
                int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                cursor.moveToFirst();
                path = cursor.getString(columnIndex);
                cursor.close();
                Log.e("takeSuccess", path + "");
            }
            if (path != null) {
                doUpload(path);
            }
        }
    }

    public static Uri getImageContentUri(Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID},
                MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    File getFilePath(String str) {
        File Gallery = new File(str);
        if (!Gallery.getParentFile().exists()) Gallery.getParentFile().mkdirs();
        return Gallery;
    }

    private void doUpload(final String pathName) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    //文件二进制数据
                    InputStream in = new FileInputStream(new File(pathName));
                    //普通字符串数据
                    Map<String, String> data = new HashMap<String, String>();
                    final String result = userService.userUpload(in, data, pathName);
                    Log.i("asdasd", result);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                if (jsonObject.getString("return_code").equals("SUCCESS")) {
                                    if (ImagePathStr.equals("1")) {
                                        imageUriStr = jsonObject.getString("return_body");
                                    } else if (ImagePathStr.equals("2")) {
                                        ImagePath = jsonObject.getString("return_body");
                                    }

                                    Toast.makeText(RegisterActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                } else if (jsonObject.getString("return_code").equals("FAIL")) {
                                    imageUriStr = "";
                                    Toast.makeText(RegisterActivity.this, jsonObject.getString("return_msg"), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(RegisterActivity.this, "上传错误", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    public void getVerification() {
        UserNetWorks.getVerification(EditTelephone.getText().toString(), new Subscriber<VerificationBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(VerificationBean verificationBean) {
                if (verificationBean.getReturn_code().equals("SUCCESS")) {
                    VerificationTextView.setEnabled(false);
                    timer = new DownTimer();
                    timer.setTotalTime(60 * Interval);
                    timer.setIntervalTime(Interval);
                    timer.setTimerLiener(new DownTimer.TimeListener() {
                        @Override
                        public void onFinish() {
                            VerificationTextView.setEnabled(true);
                            VerificationTextView.setText("获取验证码");
                        }

                        @Override
                        public void onInterval(long remainTime) {
                            VerificationTextView.setText(remainTime / 1000
                                    + "秒后" + "再试");
                        }
                    });
                    timer.start();
                    JUtils.Toast(verificationBean.getReturn_msg());
                } else if (verificationBean.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(verificationBean.getReturn_msg());
                }
            }
        });
    }

    public void getClassification() {
        UserNetWorks.getClassification("10", new Subscriber<ClassificationBean>() {

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(ClassificationBean classificationBean) {
                if ("SUCCESS".equals(classificationBean.getReturn_code())) {
                    Layout_Classification.removeAllViews();
                    List<ClassificationBean.ReturnBodyBean> list = classificationBean.getReturn_body();
                    if (list != null && list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            addOrderItem(list.get(i), Layout_Classification);
                            addDividerLine(Layout_Classification);
                        }
                    }
                }
            }
        });
    }


    /**
     * 添加分割线
     */
    public void addDividerLine(LinearLayout ll_lv) {
        View v = new View(RegisterActivity.this);
        v.setAlpha(0.5f);
        v.setBackgroundColor(RegisterActivity.this.getResources().getColor(R.color.dialogplus_card_shadow));
        v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1));
        ll_lv.addView(v);
    }

    /**
     * 添加订单
     * addOrderItem(DingDanBean.ReturnBodyBean dataBean)
     */
    public void addOrderItem(final ClassificationBean.ReturnBodyBean dataBean, LinearLayout ll_lv) {
        View view = LayoutInflater.from(RegisterActivity.this).inflate(R.layout.classification_item, null);
        TextView Text_Classification = view.findViewById(R.id.Text_Classification);
        TextView xiugai = view.findViewById(R.id.tv_xiugai);
        TextView delete = view.findViewById(R.id.tv_delete);
        xiugai.setVisibility(View.GONE);
        delete.setVisibility(View.GONE);
        Text_Classification.setText(dataBean.getSort_name());
        Text_Classification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditClassification.setText(dataBean.getSort_name());
                StrClassification = dataBean.getSort_id();
                dialog.dismiss();
            }
        });
        ll_lv.addView(view);
    }

    public void showDialog() {
        dialog.show();
    }

}
